const { merge } = require("webpack-merge");
const common = require("./webpack.common.js");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const TerserJSPlugin = require("terser-webpack-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");

module.exports = merge(common, {
  mode: "production",
  devtool: "source-map", // 源码映射
  output: {
    filename: "[name].[hash].js",
    chunkFilename: "[name].[hash].js",
  },
  optimization: {
    // optimization.minimizer: 覆盖 webpack 默认提供的优化器 压缩css
    minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
    // 分离公共依赖
    splitChunks: {
      // chunks: "async",
      cacheGroups: {
        styles: {
          name: "styles",
          test: /\.css$/,
          chunks: "all",
          enforce: true,
        },
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendors",
          chunks: "all",
        },
      },
    },
    // 将 runtime 代码拆分为一个单独的 chunk
    runtimeChunk: "single",
    // 前后两次构建，vendor hash 保持一致
    moduleIds: "hashed",
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name].[contenthash].css", // filename: "[contenthash].css" 启动长期缓存
      chunkFilename: "[id].[contenthash].css",
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
});
